package com.heima.app.gateway.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Order(0)
@Component
public class AuthorizeFilter implements GlobalFilter {

    /**
     * 全局过滤器
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //获取response对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getURI().getPath();
        //判断是否包含登录请求
        if (path.contains("login")) {
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        //非空判断
        if (StringUtils.isBlank(token)) {
            //走到这里说明是空的,返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束方法
            return response.setComplete();
        }
        try {
            //解析token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //获取有效期
            int result = AppJwtUtil.verifyToken(claimsBody);
            //判断
            if (result == 1 || result == 2) {
                //走到这里说明过期,返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束方法
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //走到这里，说明校验失败,返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束方法
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }
}
